<template>
  <div class="aq-upload-img">
    <!-- 按钮样式 -->
    <el-upload v-if="props.uploadType === 'button'" :file-list="fileList" :headers="uploadHeader"
      :action="props.uploadAction" :multiple="props.multiple" :before-remove="beforeRemove" :on-remove="handleRemove"
      :limit="props.limit" :accept="accept" :on-success="handleSuccess" :on-error="handleError"
      :before-upload="beforeUpload" :on-exceed="handleExceed" :on-progress="handleProgress">
      <el-button plain>
        <!-- 按钮要求8px间隙 -->
        <el-icon style="margin-right: 8px">
          <Upload />
        </el-icon>
        上传{{ props.buttonName }}
      </el-button>
      <template #tip>
        <div class="el-upload__tip">格式要求：{{ accept }}，数量限制{{ props.limit }}个，每个{{ props.buttonName }}小于{{
          props.uploadSize }}M</div>
      </template>
    </el-upload>
    <!-- 框样式 -->
    <el-upload v-if="props.uploadType === 'box'" list-type="picture-card" :show-file-list="true"
      :file-list="props.fileList" :headers="uploadHeader" :action="props.uploadAction" :multiple="props.multiple"
      :before-remove="beforeRemove" :on-remove="handleRemove" :limit="props.limit" :accept="accept"
      :on-preview="handlePictureCardPreview" :on-success="handleSuccess" :on-error="handleError"
      :before-upload="beforeUpload" :on-exceed="handleExceed" :on-progress="handleProgress">
      <el-icon class="btncss">
        <Plus />
      </el-icon>
      <div class="certificate">点击上传图片</div>

      <template #tip>
        <div class="el-upload__tip">额外提示语,文字过多时宽度折行xxxxxxxxxxxxxxxxxxxxxxxxxxxx</div>
      </template>
    </el-upload>
    <!-- 预览弹框 -->
    <el-image-viewer v-if="isPreviewImg" :url-list="previewImgs" :initial-index="previewIndex"
      @close="isPreviewImg = false" />
    <!-- 手动上传 -->
      <el-upload  v-if="props.uploadType === 'manual'"
          class="upload-demo"
          ref="uploadRef"
          :action="props.uploadAction"
          :auto-upload="false"
        >
          <template #trigger>
            <el-button plain>
               <el-icon class="el-icon--left"><Upload /></el-icon>上传文件
            </el-button>
  
          </template>
          <el-button class="uplcss"  type="primary" @click="submitUpload">
           确认上传
          </el-button>
    
          <template #tip>
            <div class="el-upload__tip">
              额外提示语,文字过多时宽度折行xxxxxxxxxxxxxxxxxxxxxxxxxxxx
            </div>
          </template>
    </el-upload>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from "vue";


const uploadRef = ref(); 
const submitUpload = () => {
  if (uploadRef.value) {
    console.log(uploadRef.value,'123');
    uploadRef.value.submit();
  }
};
const { proxy } = getCurrentInstance();
const props = defineProps({
  uploadType: {
    //上传类型：button-按钮型，box-框型
    type: String,
    default: "button",
  },
  limit: {
    type: Number,
    default: 10,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  fileList: {
    type: Array,
    default: [],
  },
  token: {
    type: String,
    default: "",
  },
  uploadAction: {
    type: String,
    default: "",
  },
  acceptList: {
    //文件类型数组 ['.jpg', '.png']，注意：上传类型为box模式下只能配置上传图片的格式，其它比如.rar不生效
    type: Array,
    default: [],
  },
  buttonName: {
    //按钮的名字
    type: String,
    default: "图片",
  },
  uploadSize: {
    //单个上传文件的大小MB
    type: Number,
    default: 10,
  },
});

let previewImgs = ref([]);
let previewIndex = ref(0);
let isPreviewImg = ref(false);



let accept = ref(props.acceptList.join(", "));
const emits = defineEmits(["update:imgValue"]);
const uploadHeader = {
  Authorization: props.token,
};
let fileList = ref([]);
const beforeRemove = (file, fileLists) => {
  if (file && file.status === "success") {
    return ElMessageBox.confirm(`是否要删除该${props.buttonName}`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => true)
      .catch(() => false);
  } else {
    let index = 0;
    for (const i in fileLists) {
      if (fileLists[i] == file) {
        index = i;
        break;
      }
    }
    //移出当前文件对象
    fileLists.splice(index, 1);
    return false;
  }
};
//预览
const handlePictureCardPreview = (file) => {
  if (file && file.url) {
    previewImgs.value = [file.url];
    isPreviewImg.value = true
  }
}
const handleRemove = (file) => {
  // console.log('删除', file);
  try {
    if (file.url) {
      fileList.value = fileList.value.filter((item) => item.url != file.url);
    } else {
      fileList.value = fileList.value.filter((item) => item.url != file.response.data.absolutePath);
    }
  } catch (e) {
    //TODO handle the exception
  }
};
let loading = null;
const beforeUpload = (rawFile) => {
  // 所有文件类型
  let fileType = {
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".png": "image/png",
    ".gif": "image/gif",
    ".bmp": "image/bmp",
    ".svg": "image/svg+xml",
    ".zip": "application/x-zip-compressed",
    ".rar": "application/x-rar-compressed",
    ".7z": "application/x-7z-compressed",
    ".gzip": "application/gzip",
    ".tar": "application/x-tar",
    ".pdf": "application/pdf",
    ".doc": "application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    ".docx": "application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    ".xls": "application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ".xlsx": "application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ".ppt": "application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation",
    ".pptx": "application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation",
  };
  let flag = false;
  for (let item of props.acceptList) {
    if (rawFile.type == fileType[item]) {
      flag = true;
      break;
    }
  }
  if (props.acceptList.length > 0 && !flag) {
    ElMessage.error(`只能上传${accept.value}格式${props.buttonName}`);
    return false;
  } else if (rawFile.size / 1024 / 1024 > props.uploadSize) {
    ElMessage.error(`上传${props.buttonName}大小不能超过 ${props.uploadSize}MB!`);
    return false;
  } else {
    return true;
  }
};
const handleProgress = () => {
  loading = ElLoading.service({
    text: "上传中...",
    spinner: "el-icon-loading",
  });
};
const handleSuccess = (res, file, fileLists) => {
  loading & loading.close();
  if (res.code == "SUCCESS") {
    if (fileList.value) {
      fileList.value.push({
        url: res.data.absolutePath,
        name: file.name,
      });
    } else {
      fileList.value = [
        {
          url: res.data.absolutePath,
          name: file.name,
        },
      ];
    }
    ElMessage({
      message: `${props.buttonName}上传成功!`,
      type: "success",
    });
    emits("update:imgValue", fileList);
  } else {
    let index = 0;
    for (const i in fileLists) {
      if (fileLists[i] == file) {
        index = i;
        break;
      }
    }
    //移出当前文件对象
    fileLists.splice(index, 1);
    ElMessageBox.confirm(res.msg, `${props.buttonName}上传失败`, {
      confirmButtonText: "确定",
      showCancelButton: false,
      type: "warning",
    }).then(() => { });
  }
};
const handleError = (file) => {
  loading & loading.close();
  ElMessage.error("上传失败，请重新上传!");
};
const handleExceed = (files, uploadFiles) => {
  ElMessage.error(`最多只能上传${props.limit}个${props.buttonName}!`);
};
</script>

<style lang="scss">
.uplcss{
  margin-left: 12px;
  margin-bottom: 5px;
}
.el-upload__tip {
  width: 180px !important;
  color: rgba(0, 0, 0, 0.4) !important;
  font-style: normal !important;
  font-family: 'PingFang SC' !important;
  font-weight: 400 !important;
  font-size: 12px !important;
}

.aq-upload-img {
  box-sizing: border-box;
  display: flex;

  .el-upload-list--picture-card .el-upload-list__item {
    width: 122px !important;
    height: 122px !important;
  }

  .el-upload--picture-card {
    position: relative;
    margin-right: 20px;
    --el-upload-picture-card-size: 120px !important;

    .btncss {
      position: absolute;
      top: 33px;
      left: auto;
    }

    .certificate {
      position: absolute;
      color: rgba(0, 0, 0, 0.4);
      font-size: 12px;
      font-style: normal !important;
      font-family: 'PingFang SC' !important;
      font-weight: 400 !important;
      top: 67px;
      left: auto;
    }
  }

}
</style>
